package com.suyafei.service.impl;

import com.suyafei.component.MailService;
import com.suyafei.constant.CacheKey;
import com.suyafei.enums.BizCodeEnum;
import com.suyafei.enums.SendCodeEnum;
import com.suyafei.service.NotifyService;
import com.suyafei.util.CheckUtil;
import com.suyafei.util.CommonUtil;
import com.suyafei.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-02-24 14:33
 */
@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private MailService mailService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final int CODE_EXPIRED = 60 * 1000 *10;

    private static final String SUBJECT = "请验收您的验证码";

    private static final String CONTENT = "这就是你的验证码%s";

    /**
     *
     * 1、存储验证码到缓存
     * 2、发送邮箱验证码
     *
     * @param sendCodeEnum
     * @param to
     * @return
     */
    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {

        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        //如果不为空，则判断是否60秒内重复发送
        if (StringUtils.isNotBlank(cacheValue)){
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳减去验证码发送的时间错，小于60秒，则不给重复发送
            if (CommonUtil.getCurrentTimestamp() - ttl < 1000 * 60) {
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }

        }
        String randomCode = CommonUtil.getRandomCode(6);

        String value = randomCode + "_" + CommonUtil.getCurrentTimestamp();

        redisTemplate.opsForValue().set(cacheKey, value);
        if (CheckUtil.isEmail(to)) {
            //邮箱验证码 TODO
            log.info("邮箱验证码：{}",randomCode);
//            mailService.sendMail(to, SUBJECT, String.format(CONTENT, randomCode));
            return JsonData.buildSuccess(randomCode);
        }else if (CheckUtil.isPhone(to)){

        }
        return null;
    }

    /**
     * 校验验证码
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);

        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.isNotBlank(cacheValue)) {
            String cacheCode = (cacheValue.split("_"))[0];
            if (cacheCode.equals(code)) {
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }
}
